package javax.core.storage.spring.local;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import javax.core.storage.entity.FileStorageDO;
import javax.core.storage.entity.SaveResultDO;
import javax.core.storage.service.FileStorageService;
import java.io.*;

@Component("local")
@Primary
public class LocalFileStorageImpl implements FileStorageService {

    @Override
    public File getFileByXpath(String xpath) {
        return new File(xpath);
    }

    @Override
    public FileStorageDO getOneFileById(Long id) {
        return null;
    }

    @Override
    public SaveResultDO saveFile(FileStorageDO fileStorage, InputStream fileInputStream) {
        File file = new File(fileStorage.getBucket() + fileStorage.getFilePath() + fileStorage.getFileName());
        try (OutputStream out = new FileOutputStream(file)) {
            FileCopyUtils.copy(fileInputStream, out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return SaveResultDO.ok(file.getPath());
    }
}
